# @Time   : 2022-03-03 17:00:00
# @Author : Gavin Jiang
# @Owner  : YSRD (Insights Value)

import base64
import hashlib
import hmac
import logging
from urllib import parse
import time

import requests
from configparser import ConfigParser


class DingTalkUtil:
    """
    发送钉钉机器人消息
    """

    def __init__(self, config_file_path):
        self._logger = logging.getLogger(__name__)

        cfg = ConfigParser()
        cfg.read(config_file_path)

        self.cfg = cfg

    def send_msg(self, msg, mobiles: list = None, section='basic', is_at_all=0):
        if mobiles is None:
            mobiles = str(self.cfg.get(section, 'mobiles')).split(',')

        timestamp = str(round(time.time() * 1000))

        at = {"isAtAll": is_at_all}
        if isinstance(mobiles, list) and len(mobiles) > 0:
            at['atMobiles'] = mobiles

        params = {
            "msgtype": "text", "text": {"content": msg}, "at": at
        }

        url = f"{self.cfg.get(section, 'url')}&timestamp={timestamp}&sign={self.__generate_sign(timestamp, section)}"

        resp = requests.post(url=url, json=params)

        self._logger.info(f"Send msg successfully, resp: {resp.status_code}, {resp.text}")

    def __generate_sign(self, timestamp, section):
        secret = self.cfg.get(section, 'secret')

        secret_enc = secret.encode('utf-8')
        string_to_sign = '{}\n{}'.format(timestamp, secret)
        string_to_sign_enc = string_to_sign.encode('utf-8')
        hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
        sign = parse.quote_plus(base64.b64encode(hmac_code))

        return sign
